package com.gengzp.ops.facade.impl;

import com.gengzp.api.system.SysUserRemoteService;
import com.gengzp.common.model.base.resp.GenericResp;
import com.gengzp.ops.facade.IUserFacadeService;
import com.gengzp.rpc.annotations.RpcReference;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName UserFacadeServiceImpl
 * @Description 用户门面层接口实现类
 * @Author gengzp
 * @Date 2025/6/2 16:57
 */
@Service
public class UserFacadeServiceImpl implements IUserFacadeService {

    @RpcReference
    private SysUserRemoteService sysUserRemoteService;

    @Override
    public void fillInOperatorInfo(GenericResp entity) {
        if (Objects.isNull(entity)) {
            return;
        }

        // 取出所有出现的操作人id
        List<Long> operatorUserIds = Lists.newArrayList(Long.valueOf(entity.getCreatedBy()), Long.valueOf(entity.getLastModifiedBy()));
        if (CollectionUtils.isEmpty(operatorUserIds)) {
            return;
        }

        // 查询用户id对应昵称映射
        Map<Long, String> userId2NicknameMap = sysUserRemoteService.searchUserId2NicknameMapByUserIds(operatorUserIds);

        entity.setCreatedByUserNickname(userId2NicknameMap.getOrDefault(Long.valueOf(entity.getCreatedBy()), "用户已不存在"));
        entity.setLastModifiedByUserNickname(userId2NicknameMap.getOrDefault(Long.valueOf(entity.getLastModifiedBy()), "用户已不存在"));

    }

    @Override
    public void fillInOperatorInfo(List<? extends GenericResp> entities) {
        if (CollectionUtils.isEmpty(entities)) {
            return;
        }

        // 查询用户id对应昵称映射
        Map<Long, String> userId2NicknameMap = sysUserRemoteService.searchUserId2NicknameMapByUserIds(
                entities.stream().map(v -> Lists.newArrayList(Long.valueOf(v.getCreatedBy()), Long.valueOf(v.getLastModifiedBy())))
                        .flatMap(java.util.Collection::stream).distinct().collect(Collectors.toList())
        );

        entities.forEach(v -> {
            v.setCreatedByUserNickname(userId2NicknameMap.getOrDefault(Long.valueOf(v.getCreatedBy()), "用户已不存在"));
            v.setLastModifiedByUserNickname(userId2NicknameMap.getOrDefault(Long.valueOf(v.getLastModifiedBy()), "用户已不存在"));
        });
    }

}
